﻿using System;
using UnityEngine;
using UnityEngine.PlayerLoop;

public class TimeManager : MonoBehaviour
{
    private float prevSyncTime;
    private readonly float SYNC_VALUE = 15;
    private bool initialized;
    private long serverTime;
    private float ServerTimeUpdateTime;
    public void Init()
    {
        if (initialized) return;
        initialized = false;
        prevSyncTime = 0;
        SyncTime();
    }
    
    public void SyncTime()
    {
        prevSyncTime = Time.time;
        Net.TimeSynReqMessage();
    }

    public void OnTimeSync(long time)
    {
        serverTime = time;
        ServerTimeUpdateTime = Time.time;
    }

    public long GetCurrentServerTime()
    {
        if (!initialized) return 0;
        return serverTime + (long)(Time.deltaTime - ServerTimeUpdateTime);
    }
    
    private void Update()
    {
        if (Time.time - prevSyncTime > SYNC_VALUE)
        {
            SyncTime();
        }
    }
}